<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 荐购图书
 */
class RecommendBook extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'recommend_book';

    //  protected $guarded = [];//使用模型  update 更新时，允许被全部更新，若不写，则会报错 或 没任何数据变化


    /** 
     * 用户荐购列表
     * @param page int 当前页数
     * @param limit int 分页大小
     * @param start_time string 搜索开始时间
     * @param end_time string 搜索结束时间
     * @param keywords string 搜索关键词
     * @param keywords_type string 选择搜索的字段
     * @param type  int 审核状态  0 或 不传 为全部 1 已审核   2 未审核
     * @param status 状态 1待审核 2审核通过（购买中） 3审核不通过  4 已购买 5 购买失败 
     */
    public function lists($field, $keywords, $keywords_type, $type, $status, $start_time, $end_time, $limit = 10)
    {
        if (empty($field)) {
            $field = ['id', 'book_name', 'author', 'isbn', 'number', 'status', 'reason', 'create_time', 'change_time'];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($type, $status, $start_time, $end_time) {
                if ($status) {
                    $query->where('status', $status);
                }
                if ($type) {
                    if ($type == 1) {
                        $query->where('status', '>', 1);
                    } else {
                        $query->where('status', '=', 1);
                    }
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->where(function ($query) use ($keywords_type, $keywords) {
                if ($keywords) {
                    if ($keywords_type == 'book_name') {
                        $query->where('book_name', 'like', "%$keywords%");
                    } else if ($keywords_type == 'isbn') {
                        $query->where('isbn', 'like', "%$keywords%");
                    } else if ($keywords_type == 'author') {
                        $query->where('author', 'like', "%$keywords%");
                    } else {
                        $query->where('book_name', 'like', "%$keywords%")->orWhere('isbn', 'like', "%$keywords%")->orWhere('author', 'like', "%$keywords%");
                    }
                }
            })
            ->orderBy('status')
            ->orderByDesc('number')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            $book_info = RecommendUser::select(['user_id', 'book_name', 'author', 'isbn', 'press', 'pre_time', 'price', 'intro'])->where('recom_id', $val['id'])->get()->toArray();
            $res['data'][$key]['press'] = $book_info[0]['press'];
            $res['data'][$key]['pre_time'] = $book_info[0]['pre_time'];
            $res['data'][$key]['price'] = $book_info[0]['price'];
            $res['data'][$key]['intro'] = $book_info[0]['intro'];

            foreach ($book_info as $k => $v) {
                $user_info = UserInfo::getWechatField($v['user_id'], ['nickname', 'head_img']);
                $v['nickname'] = $user_info['nickname'];
                $v['head_img'] = $user_info['head_img'];
                $res['data'][$key]['book_list'][$k] = $v;
            }
        }
        return $res;
    }
    /**
     * 审核通过与拒绝
     * @param id int 申请id  多个逗号拼接 或数组格式
     * @param status int 状态 1待审核 2审核通过 3审核不通过  4 已购买 5 购买失败
     * @param $reason 拒绝理由
     */
    public function agreeAndRefused($id, $status, $reason = '')
    {
        $id = !is_array($id) ? explode(',', $id) : $id;

        switch ($status) {
            case 2:
            case 3:
                $book_recommend = $this->select('id', 'book_name')->whereIn('id', $id)->where('status', 1)->get()->toArray();
                break;
            case 4:
            case 5:
                $book_recommend = $this->select('id', 'book_name')->whereIn('id', $id)->where('status', 2)->get()->toArray();
                break;
            default:
                throw new \Exception('参数传递错误');
        }

        if (empty($book_recommend)) {
            throw new \Exception('参数传递错误');
        }

        $data = [
            'status' => $status,
            'reason' => $status == 2 ||  $status == 4 ? '' : $reason,
            'change_time' => date("Y-m-d H:i:s", time())
        ];

        $this->whereIn('id', $id)->update($data);

        return $book_recommend;
    }

    /**
     * 获取状态
     * @param status
     */
    public function getStatusName($status, $reason = null)
    {
        $data = ['1' => '待审核', '2' => '审核通过,等待购买！', '审核未通过，原因：' . $reason, '已购买,请及时前往借阅！', '购买失败，原因：' . $reason];
        return $data[$status];
    }
}
